/* Exercise 10.3 Automatic night light */ /* Needs Port A pin 0 as an analogue input */ /* Created David Miles April 2006 */ /* Updated Ben Rowland Febuary 2014 */ #include // CONFIG1 #pragma config FOSC = HS // Oscillator Selection (HS Oscillator, High-speed crystal/resonator connected between OSC1 and OSC2 pins) #pragma config WDTE = OFF // Watchdog Timer Enable (WDT disabled) #pragma config PWRTE = OFF // Power-up Timer Enable (PWRT disabled) #pragma config MCLRE = ON // MCLR Pin Function Select (MCLR/VPP pin function is MCLR) #pragma config CP = OFF // Flash Program Memory Code Protection (Program memory code protection is disabled) #pragma config CPD = OFF // Data Memory Code Protection (Data memory code protection is disabled) #pragma config BOREN = ON // Brown-out Reset Enable (Brown-out Reset enabled) #pragma config CLKOUTEN = OFF // Clock Out Enable (CLKOUT function is disabled. I/O or oscillator function on the CLKOUT pin) #pragma config IESO = OFF // Internal/External Switchover (Internal/External Switchover mode is disabled) #pragma config FCMEN = OFF // Fail-Safe Clock Monitor Enable (Fail-Safe Clock Monitor is disabled) // CONFIG2 #pragma config WRT = OFF // Flash Memory Self-Write Protection (Write protection off) #pragma config VCAPEN = OFF // Voltage Regulator Capacitor Enable (All VCAP pin functionality is disabled) #pragma config PLLEN = OFF // PLL Enable (4x PLL disabled) #pragma config STVREN = ON // Stack Overflow/Underflow Reset Enable (Stack Overflow or Underflow will cause a Reset) #pragma config BORV = LO // Brown-out Reset Voltage Selection (Brown-out Reset Voltage (Vbor), low trip point selected.) #pragma config LVP = OFF // Low-Voltage Programming Enable (High-voltage on MCLR/VPP must be used for programming) #define _XTAL_FREQ 19660800 // Defines the hardware crystal frequency allowing the delay function to work correctly #define THRESHOLD 500 void setup_hardware (void) { ANSELA = 0x01; //Set PortA to use digital inputs RA0 is analogue ANSELB = 0x00; TRISA = 0xF1; //PORTA bits 1-3 set to outputs TRISB = 0x00; //PORTB set to all outputs ADCON0 = 0x00; //Select A0 for analogue input ADCON1 = 0xF0; //Set for right justified value and FRC conversion speed LATA = 0; LATB = 0; } int read_adc0 ( void ) { unsigned char h, l ; int result; ADCON0 = 0x01; //enable the converter ADCON0 = 0x03; //start the conversion while ( ADCON0 & 0x02 ); //wait here while the conversion runs h = ADRESH; //read the high byte l = ADRESL; //read the low byte result = (256 * h) + l; //return the result return result; } int main (void) { int v; setup_hardware (); while (1) { v = read_adc0(); if ( v < THRESHOLD ) { LATB = 255; } else { LATB = 0; } } return 0; }